package com.qingzhou.web.controller.edc;

import cn.hutool.core.util.ObjUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.qingzhou.common.enums.BusinessType;
import com.qingzhou.common.utils.SecurityUtil;
import com.qingzhou.common.web.controller.BaseController;
import com.qingzhou.common.web.domain.FileVo;
import com.qingzhou.common.web.domain.LoginUser;
import com.qingzhou.common.web.domain.SysDept;
import com.qingzhou.framework.annotation.QzLog;
import com.qingzhou.framework.config.FileConfig;
import com.qingzhou.web.repository.entity.PatientEntity;
import com.qingzhou.web.service.EdcConstants;
import com.qingzhou.web.service.PatientService;
import com.qingzhou.web.service.impl.params.request.*;
import com.qingzhou.web.service.impl.params.vo.PatientVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Result;

import java.io.File;
import java.util.List;

@Api(EdcConstants.EDC_PATIENT)
@Controller
@Mapping("edc/patient")
public class PatientController extends BaseController {

    @Inject
    PatientService patientService;
    @Inject
    FileConfig fileConfig;


    @ApiOperation("新增"+EdcConstants.EDC_PATIENT)
    @QzLog(title = "新增"+EdcConstants.EDC_PATIENT, businessType = BusinessType.INSERT)
    //@AuthPermissions("edc:patient:add")
    @Post
    @Mapping("add")
    public Result<Void> add(PatientAddForm form) {
        return toResult(patientService.add(form));
    }

    @ApiOperation("删除"+EdcConstants.EDC_PATIENT)
    @QzLog(title = "删除"+EdcConstants.EDC_PATIENT, businessType = BusinessType.DELETE)
    //@AuthPermissions("edc:patient:delete")
    @Post
    @Mapping("delete")
    public Result<Void> delete(PatientDeleteForm form) {
        return toResult(patientService.delete(form));
    }

    //@AuthPermissions("edc:patient:page")
    @Get
    @Mapping("page")
    @ApiOperation(EdcConstants.EDC_PATIENT+"分页")
    public Page<PatientEntity> page(Page<PatientEntity> page, PatientEntity patientEntity) {
        return patientService.page(page, patientEntity);
    }

    //@AuthPermissions("edc:patient:detail")
    @Get
    @Mapping("detail")
    @ApiOperation(EdcConstants.EDC_PATIENT+"详情")
    public PatientVo detail(PatientDetailForm form) {
        return patientService.detail(form);
    }

    @ApiOperation("编辑"+EdcConstants.EDC_PATIENT)
    @QzLog(title = "编辑"+EdcConstants.EDC_PATIENT, businessType = BusinessType.UPDATE)
    //@AuthPermissions("edc:patient:edit")
    @Post
    @Mapping("edit")
    public Result<Void> edit(PatientEditForm form) {
        return toResult(patientService.edit(form));
    }

    @ApiOperation("补充"+EdcConstants.EDC_PATIENT)
    @QzLog(title = "补充"+EdcConstants.EDC_PATIENT, businessType = BusinessType.INSERT)
    //@AuthPermissions("edc:patient:add")
    @Post
    @Mapping("supplement")
    public Result<Void> supplement(PatientEditForm form) {
        return toResult(patientService.supplement(form));
    }

    @ApiOperation("数据检查"+EdcConstants.EDC_PATIENT)
    @QzLog(title = "数据检查"+EdcConstants.EDC_PATIENT, businessType = BusinessType.UPDATE)
    //@AuthPermissions("edc:patient:forceEdit")
    @Post
    @Mapping("forceEdit")
    public Result<Void> forceEdit(PatientForceEditForm form) {
        return toResult(patientService.forceEdit(form));
    }

    @ApiOperation("核实"+EdcConstants.EDC_PATIENT)
    @QzLog(title = "核实"+EdcConstants.EDC_PATIENT, businessType = BusinessType.UPDATE)
    //@AuthPermissions("edc:patient:done")
    @Post
    @Mapping("done")
    public Result<Void> done(PatientDoneForm form) {
        return toResult(patientService.done(form));
    }

    @ApiOperation("终止"+EdcConstants.EDC_PATIENT)
    @QzLog(title = "终止"+EdcConstants.EDC_PATIENT, businessType = BusinessType.UPDATE)
    //@AuthPermissions("edc:patient:stop")
    @Post
    @Mapping("stop")
    public Result<Void> stop(PatientStopForm form) {
        return toResult(patientService.stop(form));
    }

    @ApiOperation("导出数据")
    @QzLog(title = "导出数据", businessType = BusinessType.EXPORT)
    //@AuthPermissions("edc:patient:stop")
    @Post
    @Mapping("export")
    public void export(PatientExportForm form) {
        patientService.export(form);
    }

    @ApiOperation("生成患者编号")
    @QzLog(title = "生成患者编号", businessType = BusinessType.OTHER)
    //@AuthPermissions("edc:patient:stop")
    @Get
    @Mapping("buildPatientCode")
    public String buildPatientCode() {
        LoginUser loginUser = SecurityUtil.getLoginUser();
        SysDept dept = loginUser.getSysUser().getDept();
        String upperCase = "KHZX";
        if (ObjUtil.isNotNull(dept)) {
            String deptName = dept.getDeptName();
            String firstLetters = getFirstLetters(deptName);
            upperCase = firstLetters.toUpperCase();
        }
        return patientService.buildPatientCode(upperCase);
    }

    @SneakyThrows
    @ApiOperation("上传文件")
    @QzLog(title = "上传文件", businessType = BusinessType.UPDATE)
    //@AuthPermissions("edc:checkRecords:stop")
    @Post
    @Mapping(path="uploadFile", multipart=true)
    public void uploadFile(PatientUploadFileForm form,Context ctx) {
        form.setAddedFileStream(ctx.files("addedFileStream"));
        patientService.uploadFile(form);
    }

    @ApiOperation("查看文件")
    //@AuthPermissions("edc:checkRecords:stop")
    @Get
    @Mapping("listFile")
    public List<FileVo> listFile(PatientListFileForm form) {
        return patientService.listFile(form);
    }

    @SneakyThrows
    @ApiOperation("下载文件(单文件)")
    @Mapping("/downloadSingle")
    public void downloadSingle(PatientDownloadSingleFileForm form,Context ctx) {
        File file = patientService.downloadSingle(form);
        ctx.outputAsFile(file);
    }

    @SneakyThrows
    @ApiOperation("下载文件(zip包)")
    @Mapping("/download")
    public void download(PatientDownloadFileForm form, Context ctx) {
        patientService.download(form);
    }

    private String getFirstLetters(String hanzi) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        StringBuilder initials = new StringBuilder();
        for (char c : hanzi.toCharArray()) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]")) { // 判断是否为汉字
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        initials.append(pinyinArray[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                initials.append(c); // 非汉字直接添加
            }
        }
        return initials.toString();
    }
}
